public class WaitDemo_线程通讯2 {
    public static void main(String[] args) throws InterruptedException {
        Object obj1 = new Object();
        Object obj2 = new Object();
        Thread t1 = new Thread(() -> {
            System.out.println("线程1开始执行");
            try {
                synchronized (obj1) {
                    System.out.println("线程1得到obj1锁");
                    synchronized (obj2) {
                        System.out.println("线程1得到obj2锁");

                        System.out.println("线程1调用obj1对象的wait方法....");
                        // 无限等待状态
                        obj1.wait();
                    }
                }
            } catch (InterruptedException e) { //接收到一个Interrupter异常
                e.printStackTrace();
            }
            System.out.println("线程1执行完成");
        }, "线程1");

        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("线程2开始执行");
                synchronized (obj1) {
                    System.out.println("线程2得到obj1锁");
                    System.out.println("线程2尝试获取obj2锁");
                    synchronized (obj2) {
                        System.out.println("线程2得到obj2锁");
                    }
                }
                System.out.println("线程2执行完成");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "线程2");
        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("main over");
    }
}
